# 导入所需的库
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris

# 1. 加载鸢尾花数据集
data = load_iris()
X = data.data  # 特征数据
y = data.target  # 目标标签

# 2. 将数据集划分为训练集和测试集（80% 训练，20% 测试）
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 3. 初始化并训练高斯朴素贝叶斯模型
nb = GaussianNB()
nb.fit(X_train, y_train)

# 4. 使用模型进行预测
y_pred = nb.predict(X_test)

# 5. 计算并输出准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型准确率: {accuracy * 100:.2f}%")

# 6. 输出分类报告（可选）
from sklearn.metrics import classification_report
print("\n分类报告:")
print(classification_report(y_test, y_pred, target_names=data.target_names))

# 7. 输出混淆矩阵（可选）
from sklearn.metrics import confusion_matrix
print("\n混淆矩阵:")
print(confusion_matrix(y_test, y_pred))
